package com.vf.common.client;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.vf.common.properties.WeChatProperties;
import com.vf.common.utils.http.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Component
public class WeChatClient {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String ACCESS_TOKEN_CACHE_KEY = "access_token";

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    //微信调用用户手机号
    public static final String WX_GET_PHONE_NUMBER = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    public static final String GET_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    /**
     * 获取用户openid
     **/
    public String getOpenId(String code){
        //调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppId());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtils.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }

    /**
     * 通过code获取用户手机号
     **/
    public String getWxUserPhoneNumber(String code){
        String accessToken = getAccessToken();
        log.debug("获取到access_token: {}", accessToken);
        if (accessToken != null) {
            String url = WX_GET_PHONE_NUMBER + accessToken;
            Map<String, String> map = new HashMap<>();
            map.put("code",code);
            String json = null;
            try {
                json = HttpClientUtils.doPost4Json(url, map);
                log.debug("微信开发服务器获取手机号--响应结果：{}",json);
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONObject jsonObject = JSON.parseObject(json);
            String phoneNumber = jsonObject.getString("phoneNumber");
            log.debug("获取到用户手机号：{}",phoneNumber);
            return phoneNumber;
        }
        return null;
    }

    /**
     * 通过appid和appSecret获取accessToken，先从缓存中获取，如果缓存中有，就用缓存的，过期了就重新获取
     **/
    public String getAccessToken(){
        String at = (String) redisTemplate.opsForValue().get(ACCESS_TOKEN_CACHE_KEY);
        if (at != null) {
            return at;
        }
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppId());
        map.put("secret",weChatProperties.getSecret());
        String res = HttpClientUtils.doGet(GET_ACCESS_TOKEN, map);
        JSONObject jsonObject = JSON.parseObject(res);
        String accessToken = (String) jsonObject.get("access_token");
        Integer expiresIn = (Integer) jsonObject.get("expires_in");
        log.debug("获取到accessToken：{}，有效时间：{}",accessToken,expiresIn);
        if (accessToken != null) {
            redisTemplate.opsForValue().set(ACCESS_TOKEN_CACHE_KEY,accessToken,expiresIn,java.util.concurrent.TimeUnit.SECONDS);
            return accessToken;
        }
        return null;
    }
}
